# src/main.py
import logging
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles

from src.core.database import engine
from src.core.logging_config import setup_logging
from src.todo import models as todo_models
from src.todo.router import router as todo_router

# --- 初始化 ---
# 在应用启动时创建数据库表
todo_models.Base.metadata.create_all(bind=engine)
# 配置日志
setup_logging()

# 创建FastAPI应用实例
app = FastAPI(
    title="Simple TodoList API",
    description="一个没有用户系统的极简待办事项应用",
    version="1.0.0",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有来源，开发时方便。生产环境应指定具体域名如 ["http://localhost:3000"]
    allow_credentials=True,
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有头部
)

# --- 事件处理 ---
@app.on_event("startup")
async def startup_event():
    logging.info("应用启动...")

@app.on_event("shutdown")
async def shutdown_event():
    logging.info("应用关闭...")

# --- API 路由 ---
app.include_router(todo_router)

# --- 静态文件 ---
# 注意：确保在项目根目录有一个 'static' 文件夹来存放静态文件 (e.g., index.html)
app.mount("/", StaticFiles(directory="static", html=True), name="static")

# # 开发模式启动
# if __name__ == "__main__":
#     import uvicorn
#
#     uvicorn.run(
#         "app:app",
#         host="127.0.0.1",
#         port=800,
#         reload=True,
#         log_level="debug"
#     )
